﻿using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using OpenIddict.Validation.AspNetCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace YDT_Distributed_Authentication.DistributedAuthentications
{
    /// <summary>
    /// 分布式权限 校验 封装
    /// </summary>
    public static class OpenIddictValidationDistributedAuthenticationWebApplicationBuilderExtenions
    {
        public static WebApplicationBuilder AddDistributedAuthenticationValidation(this WebApplicationBuilder builder)
        {
            var Configuration = builder.Configuration;

            //builder.Services.AddAuthentication();

            // 1、开启身份认证
            builder.Services.AddAuthentication(options =>
            {
                options.DefaultScheme = OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme;
            });
            // 2、使用OpenIddict实现身份认证
            builder.Services.AddOpenIddict()
                            .AddValidation(options => {
                                options.SetIssuer(Configuration["DistributedAuthentication:OpenIddictValidation:Issuer"]); // 权限服务地址
                                options.UseSystemNetHttp();
                                options.UseAspNetCore();
                                // 设置受众
                                // 1、默认一个Token访问一个微服务
                                options.AddAudiences(Configuration["DistributedAuthentication:OpenIddictValidation:Audiences"]);
                                // 2、如果希望多个Token访问一个微服务
                                //options.AddAudiences("ProductService", "AlertService");
                            });
            return builder;
        }
    }
}
